from django.shortcuts import render
from django.core.paginator import Paginator
# 引入材料类
from material.models import raw_material
from django.db.models import Max
#引入JsonResponse模块
from django.http import JsonResponse
#导入json模块
import json
#导入uuid模块
import uuid
#导入哈希模块
import hashlib
import os
from django.conf import settings
# Create your views here.

# 获取详情信息
def get_detail(materialId):
    obj_material = raw_material.objects
    # 获取过滤结果
    obj_res = obj_material.filter(materialId__icontains=materialId)

    res_list_tmp = list(obj_res.values())
    return res_list_tmp

# 获取子材料数据
def get_childs(materialId,times):
    # res_data = {}
    data = get_detail(materialId)

    print("获取数据：",data)
    res = data[0]
    if res["childrenIds"] =='':
        res["num"] = times
        print("处理到节点")
            # return res_data
    else:
        res["children"] = []
        child_list = res["childrenIds"].split("\\")
        child_num_list = res["childrenNum"].split("\\")
        for itemId in child_list:
            print("正在处理：", itemId)
            tt = int(child_num_list[child_list.index(itemId)])
            res["children"].append(get_childs(itemId,tt*times))

    return res
    # return res_data

# 搜索物品详情信息
def search_Data(request):

    data = json.loads(request.body.decode('utf-8'))
    print(data)
    # res = []
    search_materialId = data['materialId']
    num = data['num']
    try:
        res = get_childs(search_materialId,num)
        print(res)
        return JsonResponse({"code":1,"data":res})
    except Exception as e:
        return JsonResponse({"code":0,"msg":"处理异常，请联系管理员"})
    # res_list_tmp = get_detail(search_materialId)
    # if len(res_list_tmp)>0:
    #     print(res_list_tmp)
    #     # 获取子材料
    #     res_childs = res_list_tmp[0]["childrenIds"]
    #     if res_childs:
    #         res_child_list = res_childs.split('\\')
    #         print(res_child_list)


    # 创建分页



    # data['name']


# 下拉框查询
def searchDraw(request):
    data = json.loads(request.body.decode('utf-8'))
    

# 添加数据
def add_material(request):
    data = json.loads(request.body.decode('utf-8'))
    print(data)
    # 增加ID编号
    max_materialId = raw_material.objects.aggregate(Max('materialId'))['materialId__max']
    if max_materialId != None:
        data['materialId'] = max_materialId+1
    else:
        data['materialId'] = 100001
    # 添加到数据库
    try:
        obj_material = raw_material(materialId=data['materialId'],materialName=data['materialName'],materialType=data['materialType'],materialAddress=data['materialAddress'],addressLevel=data['addressLevel'],childrenNames=data['childrenNames'],childrenIds=data['childrenIds'],childrenNum=data['childrenNum'],materialImage=data['materialImage'])
        obj_material.save()
        return JsonResponse({'code':1})
    except Exception as e:
        print(e)
        return JsonResponse({'code':0,'message':"添加数据异常，请联系管理员。"})

# 上传图片
def upload_file(request):
    # 获取上传文件
    rev_file = request.FILES.get('file')
    if 'file' not in request.FILES:
        return JsonResponse({'code':0,'msg':'图片不存在'})
    new_name = get_random_str()
    file_path = os.path.join(settings.MEDIA_ROOT_MATERIAL,new_name+os.path.splitext(rev_file.name)[1])
    try:
        f=open(file_path,'wb')
        for i in rev_file.chunks():
            f.write(i)
        f.close()
        # 检查文件是否存在
        return JsonResponse({'code':1,'name':new_name+os.path.splitext(rev_file.name)[1]})
    except Exception as e:
        return JsonResponse({'code':0,'msg':"上传图片异常，请联系后台管理员"})


def get_random_str():
    uuid_val = uuid.uuid4()
    uuid_str = str(uuid_val).encode('utf-8')
    md5 = hashlib.md5()
    md5.update(uuid_str)
    return md5.hexdigest()